package com.netcracker.ui.command;

import com.netcracker.entity.Author;
import com.netcracker.util.service.AuthorService;
import com.netcracker.util.service.ServiceFacade;
import com.netcracker.util.service.exception.DataTransmittingException;
import com.netcracker.util.service.exception.NullDataException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.LoggerFactory;

public class FindAuthorCommand implements Command {
    private static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(FindAuthorCommand.class);
    private final ServiceFacade serviceFacade;

        public FindAuthorCommand(ServiceFacade serviceFacade) {
        this.serviceFacade = serviceFacade;
    }

    @Override
    public String execute(HttpServletRequest request, HttpServletResponse response) {
        AuthorService authorService = serviceFacade.getAuthorService();
        String authorName = request.getParameter("authorName");
        List<Author> authors = null;
        try {
            authors = authorService.findAuthorsByName(authorName);
        } catch (DataTransmittingException ex) {
            request.setAttribute("error", "Ошибка обращения к БД.");
            LOGGER.error("DB error: ", ex);
            return "index.jsp";
        } catch (NullDataException ex) {
            request.setAttribute("error", "Авторов не найдено.");
        }
        
        request.setAttribute("authors", authors);
        return "ResultsFound.jsp";
        
    }
    
}
